package com.ruoyi.inspection.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inspection.config.GovernTaskConfig;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.inspection.domain.GovernCheckTask;
import com.ruoyi.inspection.domain.GovernCheckTaskInfo;
import com.ruoyi.inspection.domain.GovernCheckTaskItem;
import com.ruoyi.inspection.mapper.*;
import com.ruoyi.inspection.utils.BeanUtils;
import com.ruoyi.inspection.utils.IdFactory;
import com.ruoyi.system.mapper.SysDangerMapper;
import com.ruoyi.system.mapper.SysDutyUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Api("专栏相关接口")
@RestController
@RequestMapping("/pullGovernInspectionTask")
public class GovernInspectionTaskPull {

    @Resource
    private SysDangerMapper sysDangerMapper;

    @Resource
    private SysDutyUserMapper sysDutyUserMapper;

    @Resource
    private GovernCheckTaskFirmMapper governCheckTaskFirmMapper;

    @Resource
    private GovernCheckTaskItemMapper governCheckTaskItemMapper;

    @Resource
    private GovernCheckTaskItemScoreMapper governCheckTaskItemScoreMapper;

    @Resource
    private GovernCheckTaskMapper governCheckTaskMapper;

    @Resource
    private GovernCheckTaskInfoMapper governCheckTaskInfoMapper;

    public static void main(String[] args) {
        DateTime date = DateUtil.date();
        DateTime offsetDay = DateUtil.offsetDay(date, 1);
        String beginTime = DateUtil.format(DateUtil.beginOfDay(offsetDay),"yyyyMMdd") + 000000;
        String endTime = DateUtil.format(DateUtil.endOfDay(offsetDay),"yyyyMMdd") + 000000;
        System.out.println(beginTime + "++++++++++++ " + endTime);

//        beginTime = DateUtils.dateTimeNow("yyyyMM") + "01000000";
////        String beginTime = "20240101000000";
//        endTime = DateUtils.dateTimeNow("yyyyMMdd") + "000000";
//        System.out.println(beginTime + "++++++++++++ " + endTime);
//        new GovernInspectionTaskPull().issueTask(beginTime, endTime);

        new GovernInspectionTaskPull().issueTask("20250201000000", "20250228000000");
    }

    /**
     * 每天零点触发定时任务
     */
    @ApiOperation("拉去专项检查")
    @GetMapping("/pullTask")
    @Scheduled(cron = "30 30 2 * * ?")
    public void AMFive() {
        String beginTime = DateUtils.dateTimeNow("yyyyMM") + "01000000";
//        String beginTime = "20240101000000";
        String endTime = DateUtils.dateTimeNow("yyyyMMdd") + "000000";

        // 同步检查项
        int issueTaskSize = issueTask(beginTime, endTime);
        // 同步企业与检查项关系
        int issueTaskFirmSize = issueTaskFirm(beginTime, endTime);
        // 同步检查项子任务
        issueTaskCheck(beginTime, endTime);
        // 同步任务评分规则
        issueTaskCheckScore(beginTime, endTime);

        // 新增企业专项检查任务
        if (issueTaskFirmSize>0 && issueTaskSize > 0) {
            autoGenerateTaskInfo();
        }
    }


    @GetMapping("/pullTask2")
    public void AMFive2(HttpServletRequest request) {
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        String beginTime = start + "01000000";  // yyyyMM - 20240101000000
        String endTime = end + "000000";  // yyyyMMdd - 20240122000000

        // 同步检查项
        int issueTaskSize = issueTask(beginTime, endTime);
        // 同步企业与检查项关系
        int issueTaskFirmSize = issueTaskFirm(beginTime, endTime);
        // 同步检查项子任务
        issueTaskCheck(beginTime, endTime);
        // 同步任务评分规则
        issueTaskCheckScore(beginTime, endTime);

        // 新增企业专项检查任务
        if (issueTaskFirmSize>0 && issueTaskSize > 0) {
            autoGenerateTaskInfo();
        }
    }

    /**
     * 新增企业专项检查任务
     */
    public void autoGenerateTaskInfo() {
        String beginDate = DateUtils.dateTimeNow(DateUtils.YYYY) + "-01-01 00:00:00";
        // 查询该企业的检查任务
        List<GovernCheckTask> governCheckTasks = governCheckTaskMapper.queryByCompanyAndDate(GlobalConstants.COMPANY_CODE, beginDate, null);
        if (StringUtils.isEmpty(governCheckTasks)) {
            return ;
        }

        List<GovernCheckTaskInfo> batchInsertData = new ArrayList<>();
        for (GovernCheckTask governCheckTask : governCheckTasks) {
            GovernCheckTaskInfo governCheckTaskInfo = new GovernCheckTaskInfo();
            governCheckTaskInfo.setGovernCheckTaskId(governCheckTask.getGovernCheckTaskId());
            List<GovernCheckTaskInfo> list = governCheckTaskInfoMapper.queryAllByLimit(governCheckTaskInfo);
            if (StringUtils.isNotEmpty(list)) {
                // 判断已存在企业专项检查
                continue;
            }

            BeanUtils.copyBeanProp(governCheckTaskInfo, governCheckTask);
            governCheckTaskInfo.setGovernCheckTaskTypeName(InspectionConstant.QI_YE_ZI_CHA);
            governCheckTaskInfo.setGovernTaskInfoId(IdFactory.newLongId());
            governCheckTaskInfo.setGovernCompanyStatus(0);
            governCheckTaskInfo.setGovernInvolve(1);
            governCheckTaskInfo.setGovernCreateDate(new Date());
            governCheckTaskInfo.setGovernCreateBy("admin");
            batchInsertData.add(governCheckTaskInfo);
        }

        governCheckTaskInfoMapper.insertBatch(batchInsertData);
    }


    /**
     * 接受政府下发任务  governCheckTaskMapper
     */
    public int issueTask(String beginTime,String endTime) {
        String url = GovernTaskConfig.checkTaskList;
        Map<String, Object> param = new HashMap<>();
        param.put("current",1);
        param.put("size",100);
        param.put("beginTime",beginTime);
        param.put("endTime",endTime);
        // 查询数据集集合
        JSONArray objs = new JSONArray();
        while (true) {
            JSONObject result = GovernTaskConfig.invokePost(url, param);
            if (null != result) {
                JSONArray obj = result.getJSONArray("obj");
                objs.addAll(obj);
                if (obj.size() < 100) {
                    break;
                }
            } else {
                break;
            }
        }
        if (objs.isEmpty()) {
            log.info("未查询到政府下发任务");
            return 0;
        }

        List<JSONObject> collect = objs.stream().map(JSONObject::new).filter(obj ->{
            return governCheckTaskMapper.queryByTaskId(obj.get("id").toString()) == null;
        }).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(collect)) {
            governCheckTaskMapper.insertBatchByJSON(collect);
        }
        return collect.size();
    }

    /**
     * 下发专项检查任务企业 governCheckTaskFirmMapper
     */
    public int issueTaskFirm(String beginTime,String endTime) {
        String url = GovernTaskConfig.distributeCheckCompanyList;
        Map<String, Object> param = new HashMap<>();
        param.put("current",1);
        param.put("size",1000);
        param.put("beginTime",beginTime);
        param.put("endTime",endTime);
        // 查询数据集集合
        JSONArray objs = new JSONArray();
        while (true) {
            JSONObject result = GovernTaskConfig.invokePost(url, param);
            if (null != result) {
                JSONArray obj = result.getJSONArray("obj");
                objs.addAll(obj);
                if (obj.size() < 100) {
                    break;
                }
            } else {
                break;
            }
        }
        if (objs.isEmpty()) {
            log.info("未查询到政府下发专项检查任务企业");
            return 0;
        }
        List<JSONObject> collect = objs.stream().map(JSONObject::new).filter(obj ->{
            return governCheckTaskFirmMapper.queryByTaskFirmId(obj.get("id").toString()) == null;
        }).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(collect)) {
            governCheckTaskFirmMapper.insertBatchByJSON(collect);
        }
        return collect.size();
    }

    /**
     * 下发专项检查项 governCheckTaskItemMapper
     */
    public void issueTaskCheck(String beginTime,String endTime) {
        String url = GovernTaskConfig.distributeCheckItemList;
        Map<String, Object> param = new HashMap<>();
        param.put("beginTime", beginTime);
        param.put("endTime", endTime);

        // 查询数据集集合
        JSONArray objs = new JSONArray();
        int pageSize = 100;
        int pageNum = 1;
        while (true) {
            param.put("current", pageNum);
            param.put("size", pageSize);
            JSONObject result = GovernTaskConfig.invokePost(url, param);
            if (null != result) {
                JSONArray obj = result.getJSONArray("obj");
                objs.addAll(obj);
                if (obj.size() < 100) {
                    break;
                }
                pageNum++;
            } else {
                break;
            }
        }
        if (objs.isEmpty()) {
            log.info("未查询到政府下发专项检查项");
            return;
        }
        List<JSONObject> collect = objs.stream().map(JSONObject::new).filter(obj ->{
            Object applicablePlace = obj.get("applicablePlace");
            obj.set("applicablePlace", applicablePlace==null ? "" : "null".equals(applicablePlace.toString()) ? "" : applicablePlace.toString());
            return governCheckTaskItemMapper.queryByTaskItemId(obj.get("id").toString()) == null;
        }).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(collect)) {
            governCheckTaskItemMapper.insertBatchByJSON(collect);
        }
    }

    /**
     * 下发专项检查项评分细则 governCheckTaskItemScoreMapper
     */
    public void issueTaskCheckScore(String beginTime,String endTime) {
        String url = GovernTaskConfig.distributeCheckScoreList;
        Map<String, Object> param = new HashMap<>();
        param.put("beginTime",beginTime);
        param.put("endTime",endTime);

        // 查询数据集集合
        JSONArray objs = new JSONArray();
        int pageSize = 100;
        int pageNum = 1;
        while (true) {
            param.put("current", pageNum);
            param.put("size", pageSize);
            JSONObject result = GovernTaskConfig.invokePost(url, param);
            if (null != result) {
                JSONArray obj = result.getJSONArray("obj");
                objs.addAll(obj);
                if (obj.size() < 100) {
                    break;
                }
                pageNum ++;
            } else {
                break;
            }
        }
        if (objs.isEmpty()) {
            log.info("未查询到政府下发专项检查项评分细则");
            return;
        }
        List<JSONObject> collect = objs.stream().map(JSONObject::new).filter(obj ->{
            return governCheckTaskItemScoreMapper.queryByTaskItemScoreId(obj.get("id").toString()) == null;
        }).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(collect)) {
            governCheckTaskItemScoreMapper.insertBatchByJSON(collect);
        }
    }


    private String[] getTaskType(String governTaskTypeName) {
        if ("高危细分领域安全风险专项治理".equals(governTaskTypeName)) {
            return new String[]{"企业自查","省级核查","部级督导"};
        } else if ("重点县专家指导服务".equals(governTaskTypeName)) {
            return new String[]{"企业自查","县级核查","部级督导"};
        } else {
            return new String[]{"企业自查","市级交叉检查","省级抽查","部级督导"};
        }
    }
}
